﻿using System;
using System.Linq;
using Microsoft.Web.Administration;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Tasks.IIS7
{
	[TaskName("createIISDirectory")]
	public class CreateIisVirtualDirectoryTask : BaseIisWebsiteObjectTask
	{
		[TaskAttribute("applicationVirtualPath", Required = false), StringValidator(AllowEmpty = false)]
		public string ApplicationVirtualPath { get; set; }

		protected override void ChangeIisConfiguration(Site site)
		{
			string appPath = string.IsNullOrWhiteSpace(ApplicationVirtualPath) ? "/" : ApplicationVirtualPath.Trim();

			Application rootApp = site.Applications.First(a => a.Path == appPath);

			if (rootApp.VirtualDirectories[VirtualPath] == null)
			{
				rootApp.VirtualDirectories.Add(VirtualPath, FileSystemPath);

				LogMessage("Virtual directory [{0}] created", VirtualPath);
			}
			else
			{
				string msg = string.Format("Virtual directory [{0}{1}] already exists", WebsiteName, VirtualPath);

				if (!ErrorIfAlreadyExists)
				{
					LogMessage(msg);
				}
				else
				{
					throw new Exception(msg);
				}
			}

		}

	}
}
